<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/19
 * 描述: 商品管理
 */

namespace app\result\goods;

use app\model\auto\GoodsBrand;
use app\model\goods\Goods;
use app\model\goods\GoodsCategory;
use app\model\goods\GoodsSpecPrice;
use app\result\BaseResult;
use think\facade\Db;

class GoodsActionResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new Goods();
    }

    public function save_data($args): array
    {
        $baseData = [
            'goods_id' => intval($args['goods_id'] ?? 0),
            'is_sku' => intval($args['is_sku'] ?? 0),
            'category_id' => intval($args['category_id'] ?? 0),
            'brand_id' => intval($args['brand_id'] ?? 0),
            'goods_image' => $args['goods_image'] ?? '',
            'goods_name' => $args['goods_name'] ?? '',
            'remark' => $args['remark'] ?? '',
            'click_count' => intval($args['click_count'] ?? 0),
            'store_count' => intval($args['store_count'] ?? 1),
            'goods_content' => $args['goods_content'] ?? '',
            'goods_type' => intval($args['goods_type'] ?? 1),
            'is_on_sale' => intval($args['is_on_sale'] ?? 1),
            'is_recommend' => intval($args['is_recommend'] ?? 1),
            'shipping_fee' => floatval($args['shipping_fee'] ?? 0),
            'sort' => intval($args['sort'] ?? 0),
            'sales_fake' => intval($args['sales_fake'] ?? 0),
            'sales_num' => intval($args['sales_num'] ?? 0),
            'goods_price' => floatval($args['goods_price'] ?? 0),
            'market_price' => floatval($args['market_price'] ?? 0),
            'virtual_info' => $args['virtual_info'] ?? '',
            'goods_image_list' => !empty($args['goods_image_list']) ? join(',', array_filter($args['goods_image_list'])) : '',
            'service' => !empty($args['service']) ? json_encode($args['service'], JSON_UNESCAPED_UNICODE) : '',
        ];
        $is_sku = $baseData['is_sku'];
        try {
            Db::startTrans();
            $delSpecPrice = [];//要删除的规格ID
            if ($baseData['goods_id'] > 0) {
                (new Goods())->data_update(['goods_id' => $baseData['goods_id']], $baseData);
                $goods_id = $baseData['goods_id'];

                $oldSpecPrice = (new GoodsSpecPrice())->data_list_nopage(['goods_id' => $goods_id]);
                if (!empty($oldSpecPrice)) {
                    $oldSpecPrice = array_column($oldSpecPrice, null, 'spec_key');
                }
            } else {
                unset($baseData['goods_id']);
                $goods_id = (new Goods())->data_add($baseData);
            }
            if (!$is_sku) {
                $args['sku_list'] = [[
                    'spec_key' => '默认',
                    'spec_name' => '默认',
                    'store_count' => intval($args['store_count'] ?? 0),
                    'price' => floatval($args['goods_price'] ?? 0),
                    'cost_price' => floatval($args['cost_price'] ?? 0),
                    'market_price' => floatval($args['market_price'] ?? 0),
                ]];
            }
            if (!empty($args['sku_list'])) {
                $spec_price = [];
                $allNewSpecKey = array_column($args['sku_list'], 'spec_key');
                if (!empty($oldSpecPrice)) {
                    //筛选删除
                    foreach ($oldSpecPrice as $k => $v) {
                        if (!in_array($k, $allNewSpecKey)) {
                            $delSpecPrice[] = $v['spec_id'];
                        }
                    }
                }
                foreach ($args['sku_list'] as $v) {
                    if (!empty($oldSpecPrice)) {
                        if (!empty($oldSpecPrice[$v['spec_key']]['spec_id'])) {
                            $spec_id = $oldSpecPrice[$v['spec_key']]['spec_id'];
                        }
                    }
                    $tmp = [
                        'goods_id' => $goods_id,
                        'spec_key' => $v['spec_key'],
                        'spec_name' => $v['spec_name'],
                        'store_count' => intval($v['store_count'] ?? 0),
                        'price' => floatval($v['price'] ?? 0),
                        'cost_price' => floatval($v['cost_price'] ?? 0),
                        'market_price' => floatval($v['market_price'] ?? 0),
                    ];
                    if (!empty($spec_id)) {
                        $tmp['spec_id'] = $spec_id;
                    }

                    $spec_price[] = $tmp;
                }
                $res = (new GoodsSpecPrice())->saveAll($spec_price, true);
                if (!$res) {
                    Db::rollback();
                    return self::error_return('保存规格失败');
                }
                if (!empty($delSpecPrice)) {
                    bs_log($delSpecPrice, 'del', 'err_spec_price.log');
                    $res = (new GoodsSpecPrice())->data_del([['spec_id', 'in', $delSpecPrice]]);
                    if (!$res) {
                        Db::rollback();
                        return self::error_return('删除规格失败');
                    }
                }
            }
        } catch (\Exception $e) {
            Db::rollback();
            bs_log($e->getTrace(), 'error', 'err_sql_update.log');
            return self::error_return($e->getMessage());
        }
        Db::commit();
        $this->sync_goods_base($goods_id);

        return self::success_return('保存成功', ['goods_id' => $goods_id]);
    }


    // 同步商品基本信息,针对sku多规格类型
    public function sync_goods_base($goods_id)
    {
        $modelSpecPrice = new GoodsSpecPrice();
        $spec_price = $modelSpecPrice->data_get(['goods_id' => $goods_id], 'price,market_price,store_count', 'price asc');
        if (!$spec_price) {
            $spec_price = $this->model->data_get(['goods_id' => $goods_id], 'goods_price as price,market_price,store_count');
        }
        $store_count = $modelSpecPrice->data_sum(['goods_id' => $goods_id], 'store_count');
        if (!$store_count) {
            $store_count = $this->model->get_value(['goods_id' => $goods_id], 'store_count');
        }
        (new Goods())->data_update(['goods_id' => $goods_id], [
            'goods_price' => $spec_price['price'],
            'store_count' => $store_count,
            'market_price' => $spec_price['market_price'],
        ]);
        return $this->success_return('同步成功');
    }

    public function list($args = [])
    {
        $type = trim($args['type'] ?? 'onSale');//onSale/offSale/delete
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $where = [];
        if (!empty($args['keyword'])) {
            $where[] = ['goods_id|goods_name', 'like', '%' . trim($args['keyword']) . '%'];
        }
        if (!empty($args['created_time'])) {
            $where[] = ['created_at', 'between', [$args['created_time'][0], $args['created_time'][1]]];
        }
        switch ($type) {
            case 'onSale':
                $where[] = ['is_on_sale', '=', 1];
                break;
            case 'offSale':
                $where[] = ['is_on_sale', '=', 0];
                break;
            case 'delete':
                $this->model->isWithTrashed = true;
                $where[] = ['del_time', '>', 0];
                break;
        }
        $total = $this->model->data_count($where);
        $data = $this->model->data_list($where, '*', 'goods_id desc', $page, $pageSize);
        if ($data) {
            foreach ($data as &$v) {
                $v['goods_image_list'] = $v['goods_image_list'] ? explode(',', $v['goods_image_list']) : null;
                $v['category_name'] = (new GoodsCategory())->get_value(['category_id' => $v['category_id']], 'name') ?? '';
            }
            unset($v);
        }
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data
        ]);
    }

    public function get($args = [])
    {
        $type = trim($args['type'] ?? '');
        if ($type === 'delete') {
            $this->model->isWithTrashed = true;
        }
        $goods_id = intval($args['goods_id'] ?? 0);
        $data = $this->model->data_get(['goods_id' => $goods_id]);
        if (!$data) {
            return $this->error_return('数据不存在');
        }
        $data = $data->toArray();
        $data['category_name'] = (new GoodsCategory())->get_value(['category_id' => $data['category_id']], 'name') ?? '';
        $data['sku_list'] = (new GoodsSpecPrice())->data_list_nopage(['goods_id' => $goods_id], '*', 'spec_id asc');
        if (!$data['is_sku'] && !empty($data['sku_list'])) {
            $data = array_merge($data, $data['sku_list'][0]);
        }
        $data['brand_name'] = '';
        if ($data['brand_id']) {
            $data['brand_name'] = (new GoodsBrand())->get_value(['brand_id' => $data['brand_id']], 'brand_name') ?? '';
        }
        $data['goods_image_list'] = array_filter(explode(',', $data['goods_image_list']));
        $data['goods_content'] = htmlspecialchars_decode($data['goods_content']);
        $data['service'] = $data['service'] ? @json_decode($data['service'], true) : [];
        return $this->success_return('success', $data);
    }


    public function del_data($args): array
    {
        $goods_id = intval($args['goods_id'] ?? 0);
        $model = new Goods();
        $res = $model->data_update(['goods_id' => $goods_id], ['del_time' => time(), 'is_on_sale' => 0]);
        return $this->success_return('已保存到回收站');
    }

    public function set_status($args)
    {
        $goods_id = intval($args['goods_id'] ?? 0);
        $is_on_sale = $this->model->get_value(['goods_id' => $goods_id], 'is_on_sale');
        $model = new Goods();
        $update = ['is_on_sale' => $is_on_sale == 1 ? 0 : 1];
        $res = $model->data_update(['goods_id' => $goods_id], $update);
        return $this->success_return($is_on_sale == 1 ? '已下架' : '已上架');
    }

    public function restore($args)
    {
        $goods_id = intval($args['goods_id'] ?? 0);
        $model = new Goods();
        $res = $model->restore(['goods_id' => $goods_id]);
        return $this->success_return('商品已还原到回收站');
    }
}
